package org.kernely.stream.userpage;

import org.kernely.stream.StreamBundle;
import org.kernely.ui.mvp.KernelyEventSender;
import org.kernely.ui.mvp.KernelyPresenter;

import com.vaadin.ui.Layout;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
import com.vaadin.ui.TabSheet.SelectedTabChangeListener;
import com.vaadin.ui.TabSheet.Tab;

public class StreamUserPagePresenter extends KernelyPresenter<StreamUserPageView> implements KernelyEventSender {

	private final String FAVORITES_CAPTION = "Favorites";
	private final String MESSAGES_CAPTION = "Message";
	private StreamFavoritesPresenter sfp;
	
	/**
	 * In this method, we fill the view with data.
	 */
	@Override
	public void bind() {
		
		// Create the messages tab
		final StreamMessagesPresenter smp = new StreamMessagesPresenter();
		final StreamMessagesView smv = new StreamMessagesView();
		smp.setView(smv);
		
		// Create the groups tab
		sfp = new StreamFavoritesPresenter();
		final StreamFavoritesView sfv = new StreamFavoritesView();
		sfp.setView(sfv);
		
		// Adds the tabs into the tabsheet
		view.getTabsheet().addTab((Layout)smp.getView(), this.MESSAGES_CAPTION, null);
		view.getTabsheet().addTab((Layout)sfp.getView(), this.FAVORITES_CAPTION, null);
		
		// Add a listener to update the favorites when the favorites tab is selected
		view.getTabsheet().addListener(new SelectedTabChangeListener() {
			
			/**
			 * Method called when the tab is changed.
			 */
			public void selectedTabChange(SelectedTabChangeEvent event) {
				// Get the selected tab
				TabSheet tabsheet = event.getTabSheet();
				Tab selected = tabsheet.getTab(tabsheet.getSelectedTab());
				if (selected.getCaption().equals(FAVORITES_CAPTION)){
					// Force favorites list to be calculated
					sfp.listFavorites();
				}
				else if (selected.getCaption().equals(MESSAGES_CAPTION)){
					forceMessagesRefresh();
				}
			}
		});
	}
	
	/**
	 * Broadcast an event to force the StreamMessagePresenter to reload messages.
	 */
	private void forceMessagesRefresh(){
		StreamBundle.getEventBus().broadcastEvent(new StreamMustDisplayMessagesEvent(this));
	}

}